<template>
  <div class="merchant-account">
    <!-- 账户概览 -->
    <el-row :gutter="20" class="account-overview">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="account-card">
          <template #header>
            <div class="card-header">
              <span>账户余额</span>
              <el-tag type="success">可提现</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">¥ {{ formatAmount(accountInfo.balance) }}</div>
            <div class="actions">
              <el-button type="primary" @click="handleWithdraw">提现</el-button>
              <el-button @click="handleRecharge">充值</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="account-card">
          <template #header>
            <div class="card-header">
              <span>待结算金额</span>
              <el-tag type="warning">结算中</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">¥ {{ formatAmount(accountInfo.pendingAmount) }}</div>
            <div class="desc">预计 {{ accountInfo.nextSettlementDate }} 结算</div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="account-card">
          <template #header>
            <div class="card-header">
              <span>本月收入</span>
              <el-tag type="info">统计中</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">¥ {{ formatAmount(accountInfo.monthlyIncome) }}</div>
            <div class="trend">
              <span :class="accountInfo.monthlyIncomeTrend >= 0 ? 'up' : 'down'">
                {{ accountInfo.monthlyIncomeTrend >= 0 ? '+' : '' }}{{ accountInfo.monthlyIncomeTrend }}%
              </span>
              较上月
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="account-card">
          <template #header>
            <div class="card-header">
              <span>累计收入</span>
              <el-tag type="info">总计</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">¥ {{ formatAmount(accountInfo.totalIncome) }}</div>
            <div class="desc">开店至今</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 资金流水 -->
    <el-card class="transaction-list">
      <template #header>
        <div class="card-header">
          <span>资金流水</span>
          <div class="header-actions">
            <el-radio-group v-model="transactionType" size="small">
              <el-radio-button label="all">全部</el-radio-button>
              <el-radio-button label="income">收入</el-radio-button>
              <el-radio-button label="expense">支出</el-radio-button>
            </el-radio-group>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="dateShortcuts"
              size="small"
              style="margin-left: 16px"
            />
            <el-button type="primary" @click="handleExport" style="margin-left: 16px">
              <el-icon><Download /></el-icon>导出
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="transactionList"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTransactionTypeTag(row.type)">
              {{ getTransactionTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="150" align="right">
          <template #default="{ row }">
            <span :class="row.type === 'income' ? 'income' : 'expense'">
              {{ row.type === 'income' ? '+' : '-' }}¥ {{ formatAmount(row.amount) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="balance" label="账户余额" width="150" align="right">
          <template #default="{ row }">
            ¥ {{ formatAmount(row.balance) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="说明" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createTime" label="时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getTransactionStatusTag(row.status)">
              {{ getTransactionStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.type === 'withdraw' && row.status === 'pending'"
              link
              type="primary"
              @click="handleCancelWithdraw(row)"
            >
              取消
            </el-button>
            <el-button
              link
              type="primary"
              @click="handleViewDetail(row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 提现对话框 -->
    <el-dialog
      v-model="withdrawDialog.visible"
      title="申请提现"
      width="500px"
      append-to-body
    >
      <el-form
        ref="withdrawFormRef"
        :model="withdrawForm"
        :rules="withdrawRules"
        label-width="100px"
      >
        <el-form-item label="提现金额" prop="amount">
          <el-input-number
            v-model="withdrawForm.amount"
            :min="100"
            :max="accountInfo.balance"
            :precision="2"
            :step="100"
            style="width: 200px"
          />
          <div class="form-tip">最低提现金额 100 元</div>
        </el-form-item>
        <el-form-item label="提现账户" prop="accountType">
          <el-radio-group v-model="withdrawForm.accountType">
            <el-radio label="bank">银行账户</el-radio>
            <el-radio label="alipay">支付宝</el-radio>
            <el-radio label="wechat">微信</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="withdrawForm.accountType === 'bank'">
          <el-form-item label="开户银行" prop="bankName">
            <el-input v-model="withdrawForm.bankName" placeholder="请输入开户银行" />
          </el-form-item>
          <el-form-item label="银行账号" prop="bankAccount">
            <el-input v-model="withdrawForm.bankAccount" placeholder="请输入银行账号" />
          </el-form-item>
          <el-form-item label="开户人姓名" prop="accountHolder">
            <el-input v-model="withdrawForm.accountHolder" placeholder="请输入开户人姓名" />
          </el-form-item>
        </template>
        <template v-else-if="withdrawForm.accountType === 'alipay'">
          <el-form-item label="支付宝账号" prop="alipayAccount">
            <el-input v-model="withdrawForm.alipayAccount" placeholder="请输入支付宝账号" />
          </el-form-item>
          <el-form-item label="支付宝实名" prop="alipayName">
            <el-input v-model="withdrawForm.alipayName" placeholder="请输入支付宝实名" />
          </el-form-item>
        </template>
        <template v-else-if="withdrawForm.accountType === 'wechat'">
          <el-form-item label="微信账号" prop="wechatAccount">
            <el-input v-model="withdrawForm.wechatAccount" placeholder="请输入微信账号" />
          </el-form-item>
        </template>
        <el-form-item label="提现说明" prop="remark">
          <el-input
            v-model="withdrawForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入提现说明（选填）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="withdrawDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitWithdraw">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 交易详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      title="交易详情"
      width="600px"
      append-to-body
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="交易类型">
          <el-tag :type="getTransactionTypeTag(detailData.type)">
            {{ getTransactionTypeLabel(detailData.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="交易金额">
          <span :class="detailData.type === 'income' ? 'income' : 'expense'">
            {{ detailData.type === 'income' ? '+' : '-' }}¥ {{ formatAmount(detailData.amount) }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="交易状态">
          <el-tag :type="getTransactionStatusTag(detailData.status)">
            {{ getTransactionStatusLabel(detailData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="交易时间">{{ detailData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="交易说明" :span="2">{{ detailData.description }}</el-descriptions-item>
        <el-descriptions-item label="关联订单" :span="2">
          <el-link
            v-if="detailData.orderNo"
            type="primary"
            @click="handleViewOrder(detailData.orderNo)"
          >
            {{ detailData.orderNo }}
          </el-link>
          <span v-else>-</span>
        </el-descriptions-item>
        <template v-if="detailData.type === 'withdraw'">
          <el-descriptions-item label="提现账户" :span="2">
            {{ getWithdrawAccountInfo(detailData) }}
          </el-descriptions-item>
          <el-descriptions-item label="处理时间" :span="2">
            {{ detailData.processTime || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="处理说明" :span="2">
            {{ detailData.processRemark || '-' }}
          </el-descriptions-item>
        </template>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import {
  getMerchantAccountInfo,
  getMerchantTransactions,
  applyWithdraw,
  cancelWithdraw,
  exportMerchantTransactions
} from '@/api/merchant'

// 账户信息
const accountInfo = reactive({
  balance: 0,
  pendingAmount: 0,
  nextSettlementDate: '',
  monthlyIncome: 0,
  monthlyIncomeTrend: 0,
  totalIncome: 0
})

// 交易类型
const transactionType = ref('all')

// 日期范围
const dateRange = ref([])

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  type: undefined,
  startTime: undefined,
  endTime: undefined
})

// 列表数据
const loading = ref(false)
const transactionList = ref([])
const total = ref(0)

// 提现对话框
const withdrawDialog = reactive({
  visible: false
})

// 提现表单
const withdrawFormRef = ref()
const withdrawForm = reactive({
  amount: 100,
  accountType: 'bank',
  bankName: '',
  bankAccount: '',
  accountHolder: '',
  alipayAccount: '',
  alipayName: '',
  wechatAccount: '',
  remark: ''
})

// 提现表单校验规则
const withdrawRules = {
  amount: [
    { required: true, message: '请输入提现金额', trigger: 'blur' },
    { type: 'number', min: 100, message: '最低提现金额 100 元', trigger: 'blur' }
  ],
  accountType: [
    { required: true, message: '请选择提现账户类型', trigger: 'change' }
  ],
  bankName: [
    { required: true, message: '请输入开户银行', trigger: 'blur' }
  ],
  bankAccount: [
    { required: true, message: '请输入银行账号', trigger: 'blur' },
    { pattern: /^\d{16,19}$/, message: '请输入正确的银行账号', trigger: 'blur' }
  ],
  accountHolder: [
    { required: true, message: '请输入开户人姓名', trigger: 'blur' }
  ],
  alipayAccount: [
    { required: true, message: '请输入支付宝账号', trigger: 'blur' }
  ],
  alipayName: [
    { required: true, message: '请输入支付宝实名', trigger: 'blur' }
  ],
  wechatAccount: [
    { required: true, message: '请输入微信账号', trigger: 'blur' }
  ]
}

// 详情对话框
const detailDialog = reactive({
  visible: false
})

// 详情数据
const detailData = reactive({
  type: '',
  amount: 0,
  status: '',
  createTime: '',
  description: '',
  orderNo: '',
  processTime: '',
  processRemark: '',
  accountInfo: {}
})

// 获取账户信息
const getAccountInfo = async () => {
  try {
    const res = await getMerchantAccountInfo()
    Object.assign(accountInfo, res.data)
  } catch (error) {
    console.error('获取账户信息失败:', error)
  }
}

// 获取交易列表
const getTransactionList = async () => {
  loading.value = true
  try {
    const res = await getMerchantTransactions({
      ...queryParams,
      type: transactionType.value === 'all' ? undefined : transactionType.value,
      startTime: dateRange.value?.[0],
      endTime: dateRange.value?.[1]
    })
    transactionList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取交易列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 监听交易类型变化
watch(transactionType, () => {
  queryParams.pageNum = 1
  getTransactionList()
})

// 监听日期范围变化
watch(dateRange, () => {
  queryParams.pageNum = 1
  getTransactionList()
})

// 获取交易类型标签
const getTransactionTypeTag = (type) => {
  const map = {
    income: 'success',
    expense: 'danger',
    withdraw: 'warning',
    refund: 'info'
  }
  return map[type] || 'info'
}

// 获取交易类型标签文本
const getTransactionTypeLabel = (type) => {
  const map = {
    income: '收入',
    expense: '支出',
    withdraw: '提现',
    refund: '退款'
  }
  return map[type] || type
}

// 获取交易状态标签
const getTransactionStatusTag = (status) => {
  const map = {
    success: 'success',
    pending: 'warning',
    failed: 'danger'
  }
  return map[status] || 'info'
}

// 获取交易状态标签文本
const getTransactionStatusLabel = (status) => {
  const map = {
    success: '成功',
    pending: '处理中',
    failed: '失败'
  }
  return map[status] || status
}

// 获取提现账户信息
const getWithdrawAccountInfo = (data) => {
  if (!data.accountInfo) return '-'
  const { accountType, bankName, bankAccount, accountHolder, alipayAccount, alipayName, wechatAccount } = data.accountInfo
  switch (accountType) {
    case 'bank':
      return `${bankName} (${bankAccount}) - ${accountHolder}`
    case 'alipay':
      return `支付宝 (${alipayAccount}) - ${alipayName}`
    case 'wechat':
      return `微信 (${wechatAccount})`
    default:
      return '-'
  }
}

// 格式化金额
const formatAmount = (amount) => {
  return Number(amount).toFixed(2)
}

// 提现按钮操作
const handleWithdraw = () => {
  withdrawForm.amount = 100
  withdrawForm.accountType = 'bank'
  withdrawForm.bankName = ''
  withdrawForm.bankAccount = ''
  withdrawForm.accountHolder = ''
  withdrawForm.alipayAccount = ''
  withdrawForm.alipayName = ''
  withdrawForm.wechatAccount = ''
  withdrawForm.remark = ''
  withdrawDialog.visible = true
}

// 充值按钮操作
const handleRecharge = () => {
  ElMessage.info('充值功能开发中')
}

// 提交提现
const submitWithdraw = async () => {
  if (!withdrawFormRef.value) return
  await withdrawFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await applyWithdraw(withdrawForm)
        ElMessage.success('提现申请已提交')
        withdrawDialog.visible = false
        getAccountInfo()
        getTransactionList()
      } catch (error) {
        console.error('提现申请失败:', error)
        ElMessage.error('提现申请失败')
      }
    }
  })
}

// 取消提现
const handleCancelWithdraw = async (row) => {
  try {
    await ElMessageBox.confirm('确定要取消该提现申请吗？', '提示', {
      type: 'warning'
    })
    await cancelWithdraw(row.id)
    ElMessage.success('提现申请已取消')
    getAccountInfo()
    getTransactionList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消提现失败:', error)
      ElMessage.error('取消提现失败')
    }
  }
}

// 查看详情
const handleViewDetail = (row) => {
  Object.assign(detailData, row)
  detailDialog.visible = true
}

// 查看订单
const handleViewOrder = (orderNo) => {
  // TODO: 跳转到订单详情页
  console.log('查看订单:', orderNo)
}

// 导出按钮操作
const handleExport = async () => {
  try {
    await exportMerchantTransactions({
      type: transactionType.value === 'all' ? undefined : transactionType.value,
      startTime: dateRange.value?.[0],
      endTime: dateRange.value?.[1]
    })
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getTransactionList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getTransactionList()
}

onMounted(() => {
  getAccountInfo()
  getTransactionList()
})
</script>

<style lang="scss" scoped>
.merchant-account {
  padding: 20px;

  .account-overview {
    margin-bottom: 20px;

    .account-card {
      height: 100%;
      margin-bottom: 20px;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .card-content {
        text-align: center;
        padding: 20px 0;

        .amount {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
          margin-bottom: 16px;
        }

        .desc {
          font-size: 14px;
          color: #909399;
        }

        .trend {
          font-size: 14px;
          color: #909399;

          .up {
            color: #67c23a;
          }

          .down {
            color: #f56c6c;
          }
        }

        .actions {
          display: flex;
          justify-content: center;
          gap: 10px;
        }
      }
    }
  }

  .transaction-list {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-actions {
        display: flex;
        align-items: center;
      }
    }

    .income {
      color: #67c23a;
    }

    .expense {
      color: #f56c6c;
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
  }

  // 响应式布局
  @media screen and (max-width: 768px) {
    .card-header {
      flex-direction: column;
      gap: 10px;

      .header-actions {
        width: 100%;
        flex-wrap: wrap;
        gap: 10px;

        .el-radio-group,
        .el-date-picker {
          width: 100%;
        }
      }
    }
  }
}
</style> 